<template>
  <div class="points-records">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>积分明细</h1>
        <div class="placeholder"></div>
      </div>

      <!-- 积分概览 -->
      <el-card class="points-overview-card">
        <div class="points-overview">
          <div class="current-points">
            <div class="points-number">{{ userStats.totalPoints || 0 }}</div>
            <div class="points-label">当前积分</div>
          </div>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-value">{{ userStats.earnedThisMonth || 0 }}</div>
              <div class="stat-label">本月获得</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userStats.usedThisMonth || 0 }}</div>
              <div class="stat-label">本月使用</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userStats.expiringSoon || 0 }}</div>
              <div class="stat-label">即将过期</div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 筛选条件 -->
      <el-card class="filter-card">
        <div class="filter-content">
          <div class="filter-row">
            <span class="filter-label">类型：</span>
            <el-select v-model="filters.type" placeholder="请选择类型" clearable @change="handleFilterChange">
              <el-option label="全部" value="" />
              <el-option label="获得积分" value="earn" />
              <el-option label="消费积分" value="spend" />
              <el-option label="过期扣除" value="expire" />
            </el-select>
          </div>
          <div class="filter-row">
            <span class="filter-label">时间：</span>
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleFilterChange"
            />
          </div>
          <div class="filter-actions">
            <el-button @click="resetFilters">重置</el-button>
            <el-button type="primary" @click="exportRecords" :loading="exportLoading">
              导出记录
            </el-button>
          </div>
        </div>
      </el-card>

      <!-- 积分记录列表 -->
      <div class="records-list" v-loading="loading">
        <div v-if="pointsRecords.length === 0 && !loading" class="empty-state">
          <el-empty description="暂无积分记录">
            <el-button type="primary" @click="goToEarnPoints">去赚积分</el-button>
          </el-empty>
        </div>

        <div
          v-for="record in pointsRecords"
          :key="record.id"
          class="record-item"
          @click="showRecordDetail(record)"
        >
          <div class="record-icon">
            <el-icon :color="getRecordTypeColor(record.type)" size="24">
              <component :is="getRecordTypeIcon(record.type)" />
            </el-icon>
          </div>

          <div class="record-content">
            <div class="record-header">
              <h4 class="record-title">{{ record.title }}</h4>
              <div class="record-points" :class="record.type">
                {{ record.type === 'earn' ? '+' : '-' }}{{ record.points }}
              </div>
            </div>
            <p class="record-description">{{ record.description }}</p>
            <div class="record-meta">
              <span class="record-time">{{ formatDate(record.createdAt) }}</span>
              <el-tag :type="getRecordStatusType(record.status)" size="small">
                {{ getRecordStatusText(record.status) }}
              </el-tag>
            </div>
          </div>

          <div class="record-arrow">
            <el-icon><ArrowRight /></el-icon>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore && !loading">
        <el-button @click="loadMore" :loading="loadingMore">
          加载更多
        </el-button>
      </div>
    </div>

    <!-- 积分记录详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="积分详情"
      width="500px"
    >
      <div class="record-detail" v-if="selectedRecord">
        <div class="detail-header">
          <el-icon :color="getRecordTypeColor(selectedRecord.type)" size="32">
            <component :is="getRecordTypeIcon(selectedRecord.type)" />
          </el-icon>
          <div class="detail-info">
            <h3>{{ selectedRecord.title }}</h3>
            <div class="detail-points" :class="selectedRecord.type">
              {{ selectedRecord.type === 'earn' ? '+' : '-' }}{{ selectedRecord.points }} 积分
            </div>
          </div>
        </div>

        <div class="detail-content">
          <div class="detail-row">
            <span class="label">交易类型</span>
            <span class="value">{{ getRecordTypeText(selectedRecord.type) }}</span>
          </div>
          <div class="detail-row">
            <span class="label">交易时间</span>
            <span class="value">{{ formatDateTime(selectedRecord.createdAt) }}</span>
          </div>
          <div class="detail-row">
            <span class="label">交易状态</span>
            <el-tag :type="getRecordStatusType(selectedRecord.status)" size="small">
              {{ getRecordStatusText(selectedRecord.status) }}
            </el-tag>
          </div>
          <div class="detail-row" v-if="selectedRecord.orderId">
            <span class="label">关联订单</span>
            <el-link type="primary" @click="goToOrder(selectedRecord.orderId)">
              {{ selectedRecord.orderNumber }}
            </el-link>
          </div>
          <div class="detail-row" v-if="selectedRecord.expireAt">
            <span class="label">有效期至</span>
            <span class="value">{{ formatDate(selectedRecord.expireAt) }}</span>
          </div>
          <div class="detail-row full">
            <span class="label">备注说明</span>
            <p class="description">{{ selectedRecord.description || '无备注' }}</p>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDetailDialog = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  ArrowRight,
  Plus,
  Minus,
  Gift,
  ShoppingCart,
  Clock
} from '@element-plus/icons-vue'
import { pointsApi } from '@/services/api'
import dayjs from 'dayjs'

const router = useRouter()

// 数据定义
const loading = ref(true)
const loadingMore = ref(false)
const exportLoading = ref(false)
const pointsRecords = ref([])
const userStats = ref({})
const hasMore = ref(false)
const page = ref(1)
const pageSize = ref(20)
const showDetailDialog = ref(false)
const selectedRecord = ref(null)

// 筛选条件
const filters = reactive({
  type: '',
  dateRange: null
})

// 生命周期
onMounted(() => {
  fetchPointsRecords()
  fetchUserStats()
})

// 方法定义
const fetchPointsRecords = async () => {
  try {
    loading.value = true
    
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      type: filters.type || undefined,
      startDate: filters.dateRange?.[0],
      endDate: filters.dateRange?.[1]
    }

    const response = await pointsApi.getPointsRecords(params)
    const { data, total } = response.data
    
    if (page.value === 1) {
      pointsRecords.value = data
    } else {
      pointsRecords.value.push(...data)
    }
    
    hasMore.value = pointsRecords.value.length < total
  } catch (error) {
    console.error('获取积分记录失败:', error)
    ElMessage.error('获取积分记录失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

const fetchUserStats = async () => {
  try {
    const response = await pointsApi.getPointsStatistics()
    userStats.value = response.data
  } catch (error) {
    console.error('获取积分统计失败:', error)
  }
}

const handleFilterChange = () => {
  page.value = 1
  fetchPointsRecords()
}

const resetFilters = () => {
  filters.type = ''
  filters.dateRange = null
  handleFilterChange()
}

const loadMore = () => {
  page.value++
  loadingMore.value = true
  fetchPointsRecords()
}

const exportRecords = async () => {
  try {
    exportLoading.value = true
    
    const params = {
      type: filters.type || undefined,
      startDate: filters.dateRange?.[0],
      endDate: filters.dateRange?.[1]
    }

    // 这里应该调用导出API，返回文件下载链接
    // const response = await pointsApi.exportRecords(params)
    
    // 模拟导出功能
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exportLoading.value = false
  }
}

const showRecordDetail = (record) => {
  selectedRecord.value = record
  showDetailDialog.value = true
}

const getRecordTypeIcon = (type) => {
  const iconMap = {
    earn: Plus,
    spend: ShoppingCart,
    expire: Clock
  }
  return iconMap[type] || Gift
}

const getRecordTypeColor = (type) => {
  const colorMap = {
    earn: '#67c23a',
    spend: '#e6a23c',
    expire: '#f56c6c'
  }
  return colorMap[type] || '#409eff'
}

const getRecordTypeText = (type) => {
  const textMap = {
    earn: '获得积分',
    spend: '消费积分',
    expire: '积分过期'
  }
  return textMap[type] || '其他'
}

const getRecordStatusType = (status) => {
  const typeMap = {
    completed: 'success',
    pending: 'warning',
    failed: 'danger',
    expired: 'info'
  }
  return typeMap[status] || 'info'
}

const getRecordStatusText = (status) => {
  const textMap = {
    completed: '已完成',
    pending: '处理中',
    failed: '失败',
    expired: '已过期'
  }
  return textMap[status] || '未知'
}

const goToOrder = (orderId) => {
  router.push(`/orders/${orderId}`)
}

const goToEarnPoints = () => {
  router.push('/home')
}

const handleBack = () => {
  router.back()
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}

const formatDateTime = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style lang="scss" scoped>
.points-records {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  h1 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 32px;
  }
}

.el-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.points-overview-card {
  .points-overview {
    display: flex;
    align-items: center;
    gap: 24px;

    .current-points {
      text-align: center;

      .points-number {
        font-size: 32px;
        font-weight: 600;
        color: #e6a23c;
        margin-bottom: 4px;
      }

      .points-label {
        color: #666;
        font-size: 14px;
      }
    }

    .stats-grid {
      flex: 1;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 16px;

      .stat-item {
        text-align: center;
        padding: 12px;
        background: #f8f9fa;
        border-radius: 8px;

        .stat-value {
          font-size: 18px;
          font-weight: 600;
          color: #333;
          margin-bottom: 4px;
        }

        .stat-label {
          color: #666;
          font-size: 12px;
        }
      }
    }
  }
}

.filter-card {
  .filter-content {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 16px;

    .filter-row {
      display: flex;
      align-items: center;
      gap: 8px;

      .filter-label {
        color: #666;
        font-size: 14px;
        white-space: nowrap;
      }
    }

    .filter-actions {
      margin-left: auto;
    }
  }
}

.records-list {
  .empty-state {
    padding: 60px 20px;
    text-align: center;
  }

  .record-item {
    display: flex;
    align-items: center;
    background: white;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
      transform: translateY(-1px);
    }

    .record-icon {
      margin-right: 12px;
      flex-shrink: 0;
    }

    .record-content {
      flex: 1;

      .record-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 4px;

        .record-title {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }

        .record-points {
          font-size: 16px;
          font-weight: 600;

          &.earn {
            color: #67c23a;
          }

          &.spend {
            color: #e6a23c;
          }

          &.expire {
            color: #f56c6c;
          }
        }
      }

      .record-description {
        margin: 0 0 8px 0;
        color: #666;
        font-size: 14px;
        line-height: 1.4;
      }

      .record-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .record-time {
          color: #999;
          font-size: 12px;
        }
      }
    }

    .record-arrow {
      margin-left: 12px;
      color: #ccc;
      flex-shrink: 0;
    }
  }
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.record-detail {
  .detail-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;

    .detail-info {
      flex: 1;

      h3 {
        margin: 0 0 4px 0;
        font-size: 18px;
        color: #333;
      }

      .detail-points {
        font-size: 16px;
        font-weight: 600;

        &.earn {
          color: #67c23a;
        }

        &.spend {
          color: #e6a23c;
        }

        &.expire {
          color: #f56c6c;
        }
      }
    }
  }

  .detail-content {
    .detail-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      &.full {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
      }

      .label {
        color: #666;
        font-size: 14px;
        min-width: 80px;
      }

      .value {
        color: #333;
        font-size: 14px;
        text-align: right;
      }

      .description {
        margin: 0;
        color: #666;
        font-size: 14px;
        line-height: 1.5;
        word-break: break-all;
      }
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .points-overview {
    flex-direction: column;
    gap: 16px;

    .stats-grid {
      grid-template-columns: 1fr;
      gap: 8px;
    }
  }

  .filter-content {
    flex-direction: column;
    align-items: stretch;

    .filter-row {
      justify-content: space-between;
    }

    .filter-actions {
      margin-left: 0;
      display: flex;
      gap: 8px;
    }
  }

  .record-item {
    .record-content {
      .record-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 4px;
      }
    }
  }
}
</style> 